package com.atguigu.eduservice.service.impl;

import com.atguigu.common.R;
import com.atguigu.common.exception.GuliException;
import com.atguigu.eduservice.client.VodClient;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.mapper.EduVideoMapper;
import com.atguigu.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-04-13
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    @Autowired
    private VodClient vodClient;

    //1 根据课程id删除小节
    @Override
    public void removeVideoByCourseId(String courseId) {
        //1 根据课程id把小节里面所有视频id获取出来
        QueryWrapper<EduVideo> wrapperVideo = new QueryWrapper<>();
        wrapperVideo.eq("course_id",courseId);
        List<EduVideo> eduVideoList = baseMapper.selectList(wrapperVideo);

        //封装最终所有视频id
        List<String> videoSourceIdList = new ArrayList<>();
        //从eduVideoList获取视频id
        for (int i = 0; i < eduVideoList.size(); i++) {
            //获取每个小节对象
            EduVideo eduVideo = eduVideoList.get(i);
            //从每个小节对象里面获取视频id
            String videoSourceId = eduVideo.getVideoSourceId();
            //判断小节是否有视频id
            if(!StringUtils.isEmpty(videoSourceId)) {
                //放到list集合
                videoSourceIdList.add(videoSourceId);
            }
        }

        //调用vodClient方法实现删除多个视频
        if(videoSourceIdList.size() > 0) {
            vodClient.deleteBatchVideoIds(videoSourceIdList);
        }

        //删除小节
        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        baseMapper.delete(wrapper);
    }

    //删除小节，删除阿里云视频
    @Override
    public void removeVideoId(String id) {
        //根据小节id获取小节视频id
        EduVideo eduVideo = baseMapper.selectById(id);
        String videoSourceId = eduVideo.getVideoSourceId();
        if(!StringUtils.isEmpty(videoSourceId)) {
            //根据视频id删除阿里云视频
            R result = vodClient.deleteVideoAliyun(videoSourceId);
            if(!result.getSuccess()) {
                throw new GuliException(20001,"远程调用失败");
            }
        }
        //删除小节
        int result = baseMapper.deleteById(id);
        if(result == 0) {
            throw new GuliException(20001,"删除小节失败");
        }
    }
}
